package lee.filter;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lee.model.UserDTO;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Autor zhangjiawen
 * @Date: 2020/5/29 10:16
 */
@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //解析出头中的token
        String token = request.getHeader("json-token");
        if(!StringUtils.isEmpty(token)){
            String json= Base64.decodeStr(token);
            //将token转成json对象
            JSONObject jsonObject= JSON.parseObject(json);
            //获取身份信息
            String principal = jsonObject.getString("principal");
            UserDTO userDTO=new UserDTO();
            userDTO.setUsername(principal);

            //获取权限信息
            JSONArray authoritiesArray = jsonObject.getJSONArray("authorities");
            String[] authorities=authoritiesArray.toArray(new String[authoritiesArray.size()]);
            //将用户身份权限信息填充到用户token对象中
            UsernamePasswordAuthenticationToken authenticationToken
                    =new UsernamePasswordAuthenticationToken(userDTO,null, AuthorityUtils.createAuthorityList(authorities));
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            //将authenticationToken填充到安全上下文
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            filterChain.doFilter(request,response);

        }

    }
}
